package com.example.tkserver.service.impl;

import com.example.tkserver.config.RabbitMqConfig;
import com.example.tkserver.entity.MyMessage;
import com.example.tkserver.service.interfaces.RabbitMQService;
import com.example.tkserver.entity.MyException;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;

@Service
@Log4j2
public class RabbitMQServiceImpl implements RabbitMQService {
    //日期格式化
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public String sendMsg(MyMessage message){
        try {
            rabbitTemplate.convertAndSend(RabbitMqConfig.COMMON_EXCHANGE,"",message);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException("服务器发生未知错误！");
        }
    }

    /**
     * 给用户发送欢迎消息
     * @param uid
     * @return
     */
    @Override
    public String sendHelloMsg(int uid) {
        log.info("向用户发送欢迎消息:"+uid);
        MyMessage message = new MyMessage();
        message.setSid(-1);
        message.setRid(uid);
        message.setTime(System.currentTimeMillis()/1000);
        message.setTitle("感谢使用泰科掌上宝");
        message.setAvatar("https://www.tkzsbserver.work/resources/offical_head.png");
        message.setNote("oh~亲爱的同学~终于等到你了~");
        rabbitTemplate.convertAndSend(RabbitMqConfig.COMMON_EXCHANGE,"",message);
        return null;
    }

    @Override
    public void bindExchange(String queueName, String exchangeName) {
        Queue queue = new Queue(queueName,true,false,false);
        Exchange exchange = new DirectExchange(exchangeName,true,false);
        BindingBuilder.bind(queue).to(exchange);
    }
}
